package com.yang.leather.admin.action;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.yang.leather.admin.pojo.AdminUser;


public class AccessControlFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) servletRequest;
		HttpServletResponse resp = (HttpServletResponse) servletResponse;
		HttpSession session = req.getSession(false);
		
		if (session == null) {
			resp.sendRedirect(req.getContextPath() + "/adminLogin/toLogin.do");
			return;
		}
		Object admin = session.getAttribute(AdminUser.ADMIN_KEY);
		if (admin == null || !(admin instanceof AdminUser)) {
			resp.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
		chain.doFilter(servletRequest, servletResponse);
		return;
	}

	public void destroy() {
	}
}
